package com.example.integral;

import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.util.TypedValue;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import static android.graphics.Color.*;

public class MainActivity extends Activity {
    private TextView scheduleText;
    private String text = "";
    private Integer revolution;
    private EditText revolutionText;
    private Button okButton;
    private TableLayout table;
    private List<TableRow> rows = new ArrayList<TableRow>();
    private TextView textError;
    private int currentRevolution = 0;
    private int lineCount=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        okButton = (Button) findViewById(R.id.button);
        revolutionText = (EditText) findViewById(R.id.revolution);
        table = (TableLayout) findViewById(R.id.table);
        textError = (TextView) findViewById(R.id.textError);

        okButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i("readSchedule", "onClick");
                Editable reText = revolutionText.getText();
                Log.i("readSchedule", reText.toString());
                textError.setText("");
                textError.setBackgroundColor(Color.WHITE);

                lineCount=0;
                table.removeAllViews();
                table.removeAllViewsInLayout();
                try {
                    revolution = Integer.valueOf(reText.toString().trim());
                } catch (NumberFormatException e) {
                    revolution=-1;
                }


                new AsyncTask<Void, Void, Void>(){

                    @Override
                    protected Void doInBackground(Void... params){
                        readSchedule();
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result){
                        textError.setBackgroundColor(Color.parseColor("#BDBDBD"));
                        textError.setText("Showing schedule for rev "+ currentRevolution);
                        if (lineCount==0) {

                            textError.setText("Schedule not available for rev "+ revolutionText.getText());
                        }
                        for (TableRow tr: rows) {
                            table.addView(tr, new TableLayout.LayoutParams(
                                    ViewGroup.LayoutParams.FILL_PARENT,
                                    ViewGroup.LayoutParams.WRAP_CONTENT));
                        }
                    }
                }.execute();

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        rows.clear();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void readSchedule() {
        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("http://integral.esac.esa.int/isocweb/schedule.html?action=schedule&startRevno="+revolution+"&endRevno="+revolution+"&reverseSort=&format=csv");
        //HttpGet httpGet = new HttpGet("http://integral.esac.esa.int/isocweb/schedule.html?action=schedule&startRevno=1305&endRevno=1305&reverseSort=&format=csv");
        if (revolution==-1) {
            httpGet = new HttpGet("http://integral.esac.esa.int/isocweb/schedule.html?action=schedule&startRevno=x&endRevno=x&reverseSort=&format=csv");
        }

        InputStream content = null;
        BufferedReader reader =null;

        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
             boolean first = true;
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                content = entity.getContent();
                reader = new BufferedReader(new InputStreamReader(content));
                String line;
                reader.readLine();
                int counter = 0;
                int tokenNumber = 0;
                rows.clear();
                while ((line = reader.readLine()) != null) {
                    //break comma separated line using ","
                    lineCount++;
                    counter++;
                    if (counter%2==0) {
                        RowView.color =
                                Color.parseColor("#819FF7");
                    } else {
                        RowView.color =
                                Color.WHITE;
                    }
                    StringTokenizer st = new StringTokenizer(line, ",");


                    String rev = st.nextToken().replaceAll("\"", "");
                    String start = st.nextToken().replaceAll("\"", "");
                    String end = st.nextToken().replaceAll("\"", "");
                    String exposureTime = st.nextToken().replaceAll("\"", "");
                    String source = st.nextToken().replaceAll("\"", "");
                    String ra = st.nextToken().replaceAll("\"", "");
                    String dec = st.nextToken().replaceAll("\"", "");

                    String pattern = st.nextToken().replaceAll("\"", "");
                    String pi = st.nextToken().replaceAll("\"", "");
                    String proposal = st.nextToken().replaceAll("\"", "");
                    String obs = st.nextToken().replaceAll("\"", "");
                    String notes = st.nextToken().replaceAll("\"", "");

                    currentRevolution = Integer.valueOf(rev);
                    start = start.substring(0, start.lastIndexOf("."));
                    end = end.substring(0, end.lastIndexOf("."));

                    addRow("Start time",start);
                    addRow("End time", end);
                    addRow("Exp time",exposureTime);
                    addRow("Source", source);
                    addRow("RA",ra);
                    addRow("DEC", dec);
                    addRow("Pattern",pattern);
                    addRow("PI", pi);
                    addRow("Proposal",proposal);
                    addRow("Observation", obs);
                    addRow("Notes", notes);
                }

            } else {

                Log.e("readSchedule", "Failed to download file");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {
                if (content != null) {
                    content.close();
                }
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        text = builder.toString();
    }

    private void addRow(String label, String value) {
        TableRow tr = new TableRow(this);
        TextView labelView = new HeaderView(this,label);
        TextView valueText = new RowView(this, value);
        tr.addView(labelView);
        tr.addView(valueText);
        rows.add(tr);

    }
}
